package org.apache.cordova.localfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;

import com.winner.forewide.R;

/**
 * 采用的是apache commons-net架包中的ftp工具类实现的
 * 
 * @author
 * 
 */
public class FtpCollectionUtil {

	private String username;

	private String password;

	private String ftpHostName;

	private int port = 21;

	private FTPClient ftpClient = new FTPClient();

	private FileOutputStream fos = null;

	ProgressDialog pd = null;

	int progressNum = 0;

	private Activity activityObj;

	File fileDirObj;

	Map<String, String> returnMap = new HashMap<String, String>();

	public FtpCollectionUtil(String username, String password, String ftpHostName, int port) {
		super();
		this.username = username;
		this.password = password;
		this.ftpHostName = ftpHostName;
		this.port = port;
	}

	/**
	 * 建立连接
	 */
	private void connect() {
		try {
			// System.out.println("开始连接");
			// 连接
			ftpClient.connect(ftpHostName, port);
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
			}
			// System.out.println("开始登录");
			// 登录
			ftpClient.login(username, password);
			// System.out.println("登录成功");
			ftpClient.setBufferSize(1024);
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.setControlEncoding("utf8");
		} catch (SocketException e) {

		} catch (IOException e) {

		}
	}

	/**
	 * 关闭输入输出流
	 * 
	 * @param fos
	 */
	private void close(FileOutputStream fos) {
		try {
			if (fos != null) {
				fos.close();
			}
			// System.out.println("退出登录");
			ftpClient.logout();
			// System.out.println("关闭连接");
			ftpClient.disconnect();
		} catch (IOException e) {

		}
	}

	/**
	 * 下载文件
	 * 
	 * @param fileDir
	 * @param dir1
	 * @param dir2
	 */
	public Map<String, String> downImage(Activity activity) {
		activityObj = activity;
		fileDirObj = activity.getFilesDir();
		StringBuffer sb = new StringBuffer();
		sb.append("數據已同步完成.");
		sb.append("\n是否更新，品牌/分類/類型/貨品圖片");
		Dialog dialog = new AlertDialog.Builder(activityObj).setTitle("圖片更新").setMessage(sb.toString())
				.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						pd = new ProgressDialog(activityObj);
						pd.setTitle("請稍後...");
						pd.setMessage("正在下載，品牌/分類/類型/貨品圖片");
						pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						pd.setIcon(R.drawable.icon);
						pd.setCanceledOnTouchOutside(false);
						pd.setCancelable(false);
						downImageProgress();
					}
				}).setNegativeButton("暫不", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// finish();
					}
				}).create();
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false;
				}
			}
		});
		// 显示更新框
		dialog.show();
		return returnMap;
	}

	public void downImageProgress() {
		pd.show();
		new Thread() {
			public void run() {
				try {
					String[] brandNames = {};
					String[] categoryNames = {};
					String[] productNames = {};
					connect();
					if (isDir("FWAPPLogo") && isDir("Brand")) {
						brandNames = ftpClient.listNames();
					}
					connect();
					if (isDir("FWAPPLogo") && isDir("Category")) {
						categoryNames = ftpClient.listNames();
					}
					connect();
					if (isDir("FWAPPLogo") && isDir("Product")) {
						productNames = ftpClient.listNames();
					}
					progressNum = brandNames.length + categoryNames.length + productNames.length;
					String[] dir = { "Brand", "Category", "Product" };
					Double length = 0D;
					for (int j = 0; j < dir.length; j++) {
						String dir2Obj = dir[j];
						File temp = new File(fileDirObj + "/Logo/" + dir2Obj);
						if (!temp.exists()) {
							temp.mkdirs();
						}
						connect();
						if (isDir("FWAPPLogo") && isDir(dir2Obj)) {
							String[] names = ftpClient.listNames();
							if (names != null) {
								for (int i = 0; i < names.length; i++) {
									if (!names[i].trim().equals("Thumbs.db")) {
										File localfile = new File(fileDirObj + "/Logo/" + dir2Obj, names[i]);
										if (!localfile.exists()) {
											fos = new FileOutputStream(localfile);
											ftpClient.retrieveFile(names[i], fos);
										}
										System.out.println("下载成功：" + names[i]);
										// String valueStr = "/Logo/" + dir2Obj + "/" + names[i];
										// returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
									}
									length++;
									Double progress = new Double(length / progressNum);
									progress = progress * 100;
									pd.setProgress(progress.intValue());
								}
							}
						}
					}
					close(fos);
					cancel();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 下载文件
	 * 
	 * @param fileDir
	 * @param dir1
	 * @param dir2
	 */
	public Map<String, String> downFile(Activity activity) {
		activityObj = activity;
		fileDirObj = activity.getExternalFilesDir(null);
		try {
			connect();
			if (isDir("Doc") && isDir("PDF")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("NPG") && !names[i].trim().equals("PG")
								&& !names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/PDF/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("Picture")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("NPG") && !names[i].trim().equals("PG")
								&& !names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/Picture/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("Video")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("NPG") && !names[i].trim().equals("PG")
								&& !names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/Video/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("PDF") && isDir("NPG")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/PDF/NPG/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("PDF") && isDir("PG")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/PDF/PG/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("Picture") && isDir("NPG")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/Picture/NPG/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("Picture") && isDir("PG")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/Picture/PG/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("Picture") && isDir("NPG")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/Picture/NPG/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
			connect();
			if (isDir("Doc") && isDir("Video") && isDir("PG")) {
				String[] names = ftpClient.listNames();
				if (names != null) {
					for (int i = 0; i < names.length; i++) {
						if (!names[i].trim().equals("Thumbs.db")) {
							String valueStr = "/Doc/Video/PG/" + names[i];
							returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		progressNum = returnMap.size();
		StringBuffer sb = new StringBuffer();
		sb.append("下載資訊等待時間較長，確定要下載嗎？");
		Dialog dialog = new AlertDialog.Builder(activityObj).setTitle("下載資訊").setMessage(sb.toString())
				.setPositiveButton("立即下載", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						pd = new ProgressDialog(activityObj);
						pd.setTitle("請稍後...");
						pd.setMessage("正在下載，資訊文件");
						pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						pd.setIcon(R.drawable.icon);
						pd.setCanceledOnTouchOutside(false);
						pd.setCancelable(false);
						downFileProgress();
					}
				}).setNegativeButton("暫不", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// finish();
					}
				}).create();
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false;
				}
			}
		});
		// 显示更新框
		dialog.show();
		return returnMap;
	}

	public void downFileProgress() {
		pd.show();
		new Thread() {
			public void run() {
				try {
					String[] dir = { "PDF", "Picture", "Video" };
					Double length = 0D;
					for (int j = 0; j < dir.length; j++) {
						String dir2Obj = dir[j];
						File temp = new File(fileDirObj + "/Doc/" + dir2Obj);
						if (!temp.exists()) {
							temp.mkdirs();
						}
						connect();
						if (isDir("Doc") && isDir(dir2Obj)) {
							String[] names = ftpClient.listNames();
							if (names != null) {
								for (int i = 0; i < names.length; i++) {
									if (!names[i].trim().equals("NPG") && !names[i].trim().equals("PG")
											&& !names[i].trim().equals("Thumbs.db")) {
										File localfile = new File(fileDirObj + "/Doc/" + dir2Obj, names[i]);
										if (!localfile.exists()) {
											fos = new FileOutputStream(localfile);
											ftpClient.retrieveFile(names[i], fos);
										}
										System.out.println("下载成功：" + names[i]);
										// String valueStr = "/Logo/" + dir2Obj + "/" + names[i];
										// returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
									}
									length++;
									Double progress = new Double(length / progressNum);
									progress = progress * 100;
									pd.setProgress(progress.intValue());
								}
							}
						}
						File tempNPG = new File(fileDirObj + "/Doc/" + dir2Obj + "/NPG");
						if (!tempNPG.exists()) {
							tempNPG.mkdirs();
						}
						connect();
						if (isDir("Doc") && isDir(dir2Obj) && isDir("NPG")) {
							String[] names = ftpClient.listNames();
							if (names != null) {
								for (int i = 0; i < names.length; i++) {
									if (!names[i].trim().equals("Thumbs.db")) {
										File localfile = new File(fileDirObj + "/Doc/" + dir2Obj + "/NPG", names[i]);
										if (!localfile.exists()) {
											fos = new FileOutputStream(localfile);
											ftpClient.retrieveFile(names[i], fos);
										}
										// System.out.println("下载成功：" + names[i]);
										// String valueStr = "/Logo/" + dir2Obj + "/" + names[i];
										// returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
									}
									length++;
									Double progress = new Double(length / progressNum);
									progress = progress * 100;
									pd.setProgress(progress.intValue());
								}
							}
						}
						File tempPG = new File(fileDirObj + "/Doc/" + dir2Obj + "/PG");
						if (!tempPG.exists()) {
							tempPG.mkdirs();
						}
						connect();
						if (isDir("Doc") && isDir(dir2Obj) && isDir("PG")) {
							String[] names = ftpClient.listNames();
							if (names != null) {
								for (int i = 0; i < names.length; i++) {
									if (!names[i].trim().equals("Thumbs.db")) {
										File localfile = new File(fileDirObj + "/Doc/" + dir2Obj + "/PG", names[i]);
										if (!localfile.exists()) {
											fos = new FileOutputStream(localfile);
											ftpClient.retrieveFile(names[i], fos);
										}
										System.out.println("下载成功：" + names[i]);
										// String valueStr = "/Logo/" + dir2Obj + "/" + names[i];
										// returnMap.put('"' + names[i] + '"', '"' + valueStr + '"');
									}
									length++;
									Double progress = new Double(length / progressNum);
									progress = progress * 100;
									pd.setProgress(progress.intValue());
								}
							}
						}
					}
					close(fos);
					cancel();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.cancel();
		}
	};

	public void cancel() {
		new Thread() {
			public void run() {
				Message message = handler.obtainMessage();
				handler.sendMessage(message);
			}
		}.start();
	}

	// 判断是否是目录
	public boolean isDir(String fileName) {
		boolean falg = false;
		try {
			// 切换目录，若当前是目录则返回true,否则返回false。
			falg = ftpClient.changeWorkingDirectory(fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return falg;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFtpHostName() {
		return ftpHostName;
	}

	public void setFtpHostName(String ftpHostName) {
		this.ftpHostName = ftpHostName;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

}